package cn.imatu.framework.lock.model;

import cn.imatu.framework.lock.exception.LockException;
import cn.imatu.framework.tool.core.exception.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.redis.util.RedisLockRegistry;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * @author shenguangyang
 */
@Slf4j
public class IntegrationRedisLock extends LockTemplate {
    private final Lock lock;

    public IntegrationRedisLock(String lockKey, RedisLockRegistry redisLockRegistry) {
        super(lockKey);
        Assert.notNull(redisLockRegistry, "redisLockRegistry is null");
        // registryKey和lockKey自动冒号连接，最终key为REDIS_LOCK:lockKey, 值为uuid
        this.lock = redisLockRegistry.obtain(lockKey);
    }

    @Override
    public void unlock() {
        lock.unlock();
    }

    @Override
    public void lock() {
        try {
            lock.lock();
        } catch (Exception e) {
            log.error("get lock fail, msg: {}", e.getMessage());
            throw new LockException("get lock fail");
        }
    }

    @Override
    public boolean isLocked() {
        throw new UnsupportedOperationException("IntegrationRedisLock no support isLocked");
    }

    @Override
    public boolean tryLock(long waitTime, TimeUnit unit) {
        try {
            return lock.tryLock(waitTime, unit);
        } catch (Exception e) {
            log.error("get lock fail, msg: {}", e.getMessage());
            throw new LockException("get lock fail");
        }
    }
}
